package JTreeSample;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
/**
 *
 * @author user18
 */
public class MhsTree implements TreeSelectionListener{
 public JTree tree;
 public JLabel nim,nama;
 
 public MhsTree(){
   DefaultMutableTreeNode root = new DefaultMutableTreeNode("Mahasiswa");
   MhsNode node1 = new MhsNode("0210630064", "Imam F");
   MhsNode node2 = new MhsNode("0210630065", "Imam S");
   MhsNode node3 = new MhsNode("0210630066", "Indriati");
   root.add(node1);
   root.add(node2);
   root.add(node3);
 
   DefaultTreeModel model = new DefaultTreeModel(root);
   tree = new JTree(model);
   tree.addTreeSelectionListener(this);
 
   JPanel panel = new JPanel();
   nim = new JLabel("nim");
   nama = new JLabel("nama");
   panel.add(tree);
   panel.add(nim);
   panel.add(nama);
 
   JFrame frame = new JFrame();
     frame.getContentPane().add(panel);
     frame.setSize(800, 600);
     frame.setVisible(true);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 public static void main(String[] args){
     MhsTree mhsTree = new MhsTree();
     
     
        
        
 }
 
@Override
 public void valueChanged(TreeSelectionEvent tse) {
    MhsNode node = (MhsNode) tree.getLastSelectedPathComponent();
    nim.setText(node.getNim());
    nama.setText(node.getNama());
 }
}
 
class MhsNode extends DefaultMutableTreeNode {
  private String nim;
  private String nama;
 
  public MhsNode(String nim, String nama) {
     super(nama);
     this.nim = nim;
     this.nama = nama;
  }
 
  public String getNama() {
     return nama;
  }
 
  public void setNama(String nama) {
     this.nama = nama;
  }
 
  public String getNim() {
     return nim;
  }
 
  public void setNim(String nim) {
     this.nim = nim;
  }
 
}